package servlet;

import dao.IRainQualityDao;
import dao.impl.RainQualityDaoImpl;
import entity.RainQuality;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

// 该Servlet负责处理与雨质列表相关的请求
@WebServlet(urlPatterns = "/RainQualityList", loadOnStartup = 1)
public class RainQualityListServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private IRainQualityDao rainQualityDao;

    // 构造函数，初始化RainQualityDao
    public RainQualityListServlet() {
        super();
        rainQualityDao = new RainQualityDaoImpl();
    }

    // Servlet的初始化方法，用于Servlet的初始化
    @Override
    public void init() throws ServletException {
        super.init();
        System.out.println("RainQualityListServlet init() called.");
    }

    // 处理GET请求的方法，用于展示所有雨质记录
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("RainQualityListServlet doGet() called.");

        try {
            // 查询所有雨质记录
            List<RainQuality> rainQualities = rainQualityDao.findAll();
            // 将查询结果放入请求属性中
            request.setAttribute("rainQualities", rainQualities);
            // 将请求转发到RainQualityList.jsp页面
            request.getRequestDispatcher("/RainQualityList.jsp").forward(request, response);
        } catch (Exception e) {
            // 异常处理
            e.printStackTrace();
            request.setAttribute("error", "没有数据");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
        }
    }
}
